package com.xhsj.user.hr.system.service;

import com.alibaba.fastjson.JSONArray;
import com.xhsj.user.hr.base.BaseParam;
import com.xhsj.user.hr.process.base.BaseProcessService;
import com.xhsj.user.hr.process.dto.processDefinition.HandleAuditDto;
import com.xhsj.user.hr.process.hrLeaveProcess.mapper.TbHrApprovalLeaveApplyMapper;
import com.xhsj.user.hr.process.hrLeaveProcess.query.FirstProcessNodeIdQuery;
import com.xhsj.user.hr.process.message.service.TbProjectMessageService;
import com.xhsj.user.hr.process.processDefinition.entity.TbGlobalApprovalTask;
import com.xhsj.user.hr.process.processDefinition.mapper.TbGlobalWorkFlowNodeMapper;
import com.xhsj.user.hr.process.processDefinition.query.ProcessNodeQuery;
import com.xhsj.user.hr.process.processDefinition.service.TbGlobalApprovalTaskService;
import com.xhsj.user.hr.process.query.ApprovalQuery;
import com.xhsj.user.security.entity.LoginUser;
import com.xhsj.user.hr.system.entity.TbHrApprovalDimissionApply;
import com.xhsj.user.hr.system.entity.TbHrApprovalDimissionHandoverApply;
import com.xhsj.user.hr.system.entity.TbHrDemandApply;
import com.xhsj.user.hr.system.entity.TbHrDemandApplyDetail;
import com.xhsj.user.hr.system.mapper.TbGlobalRoleMapper;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.hr.system.mapper.TbHrDemandApplyDetailMapper;
import com.xhsj.user.hr.system.mapper.TbHrDemandApplyMapper;
import com.xhsj.user.hr.system.service.TbHrDemandApplyService;
import com.xhsj.user.hr.base.BaseService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xhsj.user.hr.system.vo.DemandApplyAuditTaskVo;
import com.xhsj.user.hr.system.vo.DemandProcessAuditVo;
import com.xhsj.user.utils.MessageConstant;
import com.xhsj.user.utils.StringUtils;
import com.xhsj.user.utils.UserUtils;
import org.springframework.stereotype.Service;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.io.Serializable;
import java.util.concurrent.CompletableFuture;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import lombok.extern.slf4j.Slf4j;
/**
 * <p>
 * 需求申请表 服务实现类
 * </p>
 *
 * @author suxiaolin
 * @since Nov 11, 2020 10:53:06 AM
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
//@CacheConfig(cacheNames = "TbHrDemandApply")
public class TbHrDemandApplyService extends BaseProcessService<TbHrDemandApplyMapper, TbHrDemandApply> {
    @Autowired
    private TbHrDemandApplyMapper dao;

    @Autowired
    private TbGlobalUserMapper tbGlobalUserMapper;

    @Autowired
    private TbHrDemandApplyDetailService tbHrDemandApplyDetailService;

    @Autowired
    private TbHrDemandApplyDetailMapper tbHrDemandApplyDetailMapper;

    @Autowired
    private TbProjectMessageService tbProjectMessageService;

    @Autowired
    private TbGlobalApprovalTaskService tbGlobalApprovalTaskService;

    @Autowired
    private TbHrApprovalLeaveApplyMapper tbHrApprovalLeaveApplyMapper;

	/**
	 * 保存
	 * @author suxiaolin
	 * @date Nov 11, 2020 10:53:06 AM
	 */
    @Override
    //@CacheEvict(cacheNames="TbHrDemandApply", allEntries=true)
    public boolean save(TbHrDemandApply entity) {
        if (StringUtils.isNotBlank(entity.getId())) {
            tbHrDemandApplyDetailMapper.delByApplyId(entity.getId());
        }
        boolean save = super.save(entity);
        if (save) {
            List<TbHrDemandApplyDetail> applyDetailList = entity.getApplyDetailList();
            for (TbHrDemandApplyDetail tbHrDemandApplyDetail : applyDetailList) {
                tbHrDemandApplyDetail.setDemandApplyId(entity.getId());
                tbHrDemandApplyDetail.setCreateBy(entity.getCreateBy());
                tbHrDemandApplyDetail.setCreateDate(new Date());
                tbHrDemandApplyDetail.setUpdateBy(entity.getUpdateBy());
                tbHrDemandApplyDetail.setUpdateDate(new Date());
            }
            tbHrDemandApplyDetailService.saveBatch(applyDetailList);
        }
        return true;
    }

    /**
     * 保存
     * @author 苏小林
     * @date 2020/11/16 9:52
     * @param: entity
     * @return: boolean
     */
    public boolean saveData(TbHrDemandApply entity) throws Exception {
        if (StringUtils.isNotBlank(entity.getId())) {
            tbHrDemandApplyDetailMapper.delByApplyId(entity.getId());
        }
        boolean save = super.save(entity);
        if (save) {
            List<TbHrDemandApplyDetail> applyDetailList = entity.getApplyDetailList();
            for (TbHrDemandApplyDetail tbHrDemandApplyDetail : applyDetailList) {
                tbHrDemandApplyDetail.setDemandApplyId(entity.getId());
                tbHrDemandApplyDetail.setCreateBy(entity.getCreateBy());
                tbHrDemandApplyDetail.setCreateDate(new Date());
                tbHrDemandApplyDetail.setUpdateBy(entity.getUpdateBy());
                tbHrDemandApplyDetail.setUpdateDate(new Date());
            }
            tbHrDemandApplyDetailService.saveBatch(applyDetailList);

            if (entity.getSubmitStatus() == 2) { // 提交
                this.startProcess(entity);
            }
        }
        return true;
    }

    /**
     * 流程启动
     * @author 苏小林
     * @date 2020/11/16 9:53
     * @param: entity
     */
    private void startProcess(TbHrDemandApply entity) throws Exception {
        LoginUser loginAppUser = UserUtils.getLoginAppUser();
        Long userId = loginAppUser.getUserId();
        HandleAuditDto handleAuditDto = new HandleAuditDto(entity.getId(), userId, userId, 11);
        // 查询软件部的流程启动
        ProcessNodeQuery processNodeQuery = super.startHandleAudit(handleAuditDto, 4L);
        entity.setBusinessId(handleAuditDto.getBusinessId());
        // 修改申请信息
        this.updateInfoById(entity,processNodeQuery);

        // 发送消息
        ApprovalQuery approvalQuery =
                new ApprovalQuery(handleAuditDto.getDataId(),
                        MessageConstant.MSG_4,
                        processNodeQuery.getUserId(),
                        processNodeQuery.getRoleIds(),
                        4,
                        UserUtils.getLoginAppUser().getUserId(),
                        UserUtils.getLoginAppUser().getFullName());
        this.sendMessage(approvalQuery);
    }

    public void sendMessage(ApprovalQuery approvalQuery) {
        //保存消息
        CompletableFuture<Void> f = CompletableFuture.runAsync(() -> {
            tbProjectMessageService.sendMessageCommon(approvalQuery);
        });
    }



    /**
     * 通过id修改数据
     * @author 苏小林
     * @date 2020/11/16 10:12
     * @param: entity
     * @param: processNodeQuery
     */
    private void updateInfoById(TbHrDemandApply entity, ProcessNodeQuery processNodeQuery) {
        TbHrDemandApply tbHrDemandApply = new TbHrDemandApply();
        tbHrDemandApply.setId(entity.getId());
        tbHrDemandApply.setBusinessId(entity.getBusinessId());
        tbHrDemandApply.setNodeId(processNodeQuery.getNodeId());
        tbHrDemandApply.setNodeName(processNodeQuery.getNodeName());
        tbHrDemandApply.setUpdateBy(UserUtils.getLoginAppUser().getUserId());
        tbHrDemandApply.setUpdateDate(new Date());
        this.updateById(tbHrDemandApply);
    }


    /**
	 * 通过id获取数据
	 * @author suxiaolin
	 * @date Nov 11, 2020 10:53:06 AM
	 */
    @Override
    //@Cacheable(key = "#id",sync = true)
    public TbHrDemandApply getById(Serializable id) {
        TbHrDemandApply tbHrDemandApply = super.getById(id);
        List<TbHrDemandApplyDetail> list = tbHrDemandApplyDetailService.getByApplyId((Long) id);
        tbHrDemandApply.setApplyDetailList(list);
        return tbHrDemandApply;
    }

	/**
	 * 通过id删除数据
	 * @author suxiaolin
	 * @date Nov 11, 2020 10:53:06 AM
	 */
    @Override
    //@CacheEvict(cacheNames="TbHrDemandApply", allEntries=true)
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

	/**
	 * 批量删除数据
	 * @author suxiaolin
	 * @date Nov 11, 2020 10:53:06 AM
	 */
    //@CacheEvict(cacheNames="SysDict", allEntries=true)
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        return super.removeByIds(idList);
    }

	/**
	 * 分页查询数据
	 * @author suxiaolin
	 * @date Nov 11, 2020 10:53:06 AM
	 */
    //@Cacheable(key = "#data",sync = true)
    public IPage<TbHrDemandApply> selectPage(Map<String,Object> data) {
        int currentPage=1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage=(Integer) data.get("page");
        }
        int pageSize=20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize=(Integer) data.get("size");
        }

        TbHrDemandApply entity = JSON.parseObject(JSON.toJSONString(data), TbHrDemandApply.class);
        Page<TbHrDemandApply> page = new Page(currentPage,pageSize);
        QueryWrapper<TbHrDemandApply> wrapper = new QueryWrapper(entity);
        wrapper.eq("create_by",UserUtils.getLoginAppUser().getUserId());
        return super.selectPage(page, wrapper);
    }

	/**
	 * 查询所有数据
	 * @author suxiaolin
	 * @date Nov 11, 2020 10:53:06 AM
	 */
    @Override
    //@Cacheable(value = "TbHrDemandApply",sync = true)
    public List<TbHrDemandApply> selectAll() {
        return super.selectAll();
    }


    /**
     * 通过id删除数据
     * @author 苏小林
     * @date 2020/11/11 17:58
     * @param: id
     */
    public void delById(Long id) {
        dao.delById(id);
    }

    /**
     * 查询待审核任务
     * @author 苏小林
     * @date 2020/11/16 10:45
     * @param: baseParam
     * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.xhsj.user.hr.system.vo.DemandApplyAuditTaskVo>
     */
    public IPage<DemandApplyAuditTaskVo> findDemandApplyRunTask(BaseParam data) {
        Page<TbHrApprovalDimissionApply> page = new Page(data.getPage(),data.getSize());

        Long userId = UserUtils.getLoginAppUser().getUserId();
        List<Long> roleIds = tbGlobalUserMapper.getRoleIdsByUserId(userId);
        return dao.findDemandApplyRunTask(page,userId,roleIds);
    }

    /**
     * 流程处理
     * @author 苏小林
     * @date 2020/11/16 13:30
     * @param: handleAuditDto
     */
    public void processAudit(DemandProcessAuditVo handleAuditDto) throws Exception {
        ProcessNodeQuery processNodeQuery = super.handleAudit(handleAuditDto);

        if (handleAuditDto.getNodeId() == 2) {
            List<TbHrDemandApplyDetail> applyDetailList = handleAuditDto.getApplyDetailList();
            if (applyDetailList != null && applyDetailList.size() > 0) {
                tbHrDemandApplyDetailService.saveOrUpdateBatch(applyDetailList);
            }

        }

        TbHrDemandApply entity = new TbHrDemandApply();
        entity.setId(handleAuditDto.getDataId());
        entity.setBusinessId(handleAuditDto.getBusinessId());
        // 修改招聘申请信息
        this.updateInfoById(entity,processNodeQuery);

        String fullName = tbHrApprovalLeaveApplyMapper.getFullNameByDataId(handleAuditDto.getDataId(),"tb_hr_demand_apply");
        // 发送消息
        ApprovalQuery approvalQuery =
                new ApprovalQuery(handleAuditDto.getDataId(), MessageConstant.MSG_4, processNodeQuery.getUserId(),
                        processNodeQuery.getRoleIds(), 4, UserUtils.getLoginAppUser().getUserId(),fullName);
        this.sendMessage(approvalQuery);
    }

    /**
     * 查询历史任务
     * @author 苏小林
     * @date 2020/11/16 13:30
     * @param: baseParam
     * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.xhsj.user.hr.system.vo.DemandApplyAuditTaskVo>
     */
    public IPage<DemandApplyAuditTaskVo> findDemandApplyHiTask(BaseParam data) {
        Page<TbHrApprovalDimissionApply> page = new Page(data.getPage(),data.getSize());

        Long userId = UserUtils.getLoginAppUser().getUserId();
        return dao.findDemandApplyHiTask(page,userId);
    }

    /**
     * 重新提交
     * @author 苏小林
     * @date 2020/11/16 16:23
     * @param: data
     */
    public void reSubmit(TbHrDemandApply data) throws Exception {
        // 删除流程
        Long processTaskId = data.getProcessTaskId();
        tbGlobalApprovalTaskService.delById(processTaskId);
        // 删除之前提交的数据
        dao.delById(data.getId());
        // 保存新数据
        data.setId(null);
        this.saveData(data);


    }

    /**
     * 作废申请
     * @author 苏小林
     * @date 2020/11/16 16:53
     * @param: processTaskId
     * @param: dataId
     */
    public void disable(Long processTaskId, Long dataId) {
        tbGlobalApprovalTaskService.delById(processTaskId);
        dao.delById(dataId);
    }
}
